﻿using ExpressesClass.BestApi.Utils;
using ExpressesClass.Method;
using ExpressesClass.Model;
using OFFICE_Helper.Util;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace OFFICE_Helper.Forms
{
    public partial class KddhForm : Form
    {
        #region 变量
        private MainForm mainForm;

        private List<Kddh> list_kddh;
        private List<Kddh> list_kddh_show;
        private Kddh.ScenariosType scenariosType;

        private string ClickCellVal;
        #endregion

        #region 方法
        public KddhForm(MainForm mainForm, Kddh.ScenariosType scenariosType)
        {
            InitializeComponent();
            this.mainForm = mainForm;
            this.scenariosType = scenariosType;
            list_kddh = new List<Kddh>();
            list_kddh_show = new List<Kddh>();
        }
        private void InitCtrl()
        {
            dtp_begin.Format = DateTimePickerFormat.Custom;
            dtp_begin.CustomFormat = "yyyy-MM-dd";
            dtp_end.Format = DateTimePickerFormat.Custom;
            dtp_end.CustomFormat = "yyyy-MM-dd";
            dtp_begin.Value = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd 00:00:00"));
            dtp_end.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));

            ConfigurationManager.RefreshSection("appSettings");
            chb_showPrinted.Checked = bool.Parse(ConfigurationManager.AppSettings["isShowPrint"].ToString());
            chb_showCanceled.Checked = bool.Parse(ConfigurationManager.AppSettings["isShowCancel"].ToString());

            InitKddh();
        }
        private void InitKddh()
        {
            dgv_kddh.DataSource = new List<Kddh>();
            dgv_kddh.Columns["orderId"].Visible = false;
            dgv_kddh.Columns["markDestination"].Visible = false;
            dgv_kddh.Columns["sortingCode"].Visible = false;
            dgv_kddh.Columns["pkgCode"].Visible = false;
            dgv_kddh.Columns["billProvideSiteName"].Visible = false;
            dgv_kddh.Columns["billProvideSiteCode"].Visible = false;
            dgv_kddh.Columns["proCode"].Visible = false;
            dgv_kddh.Columns["proName"].Visible = false;
            dgv_kddh.Columns["destRouteLabel"].Visible = false;
            dgv_kddh.Columns["destTeamCode"].Visible = false;
            dgv_kddh.Columns["codingMapping"].Visible = false;
            dgv_kddh.Columns["sourceTransferCode"].Visible = false;
            dgv_kddh.Columns["abFlag"].Visible = false;
            dgv_kddh.Columns["twoDimensionCode"].Visible = false;
            dgv_kddh.Columns["codingMappingOut"].Visible = false;
            dgv_kddh.Columns["xbFlag"].Visible = false;
            dgv_kddh.Columns["printIcon"].Visible = false;
            dgv_kddh.Columns["sendPostcode"].Visible = false;
            dgv_kddh.Columns["sendProvince"].Visible = false;
            dgv_kddh.Columns["sendCity"].Visible = false;
            dgv_kddh.Columns["sendCounty"].Visible = false;
            dgv_kddh.Columns["sendCompany"].Visible = false;
            dgv_kddh.Columns["receiveCompany"].Visible = false;
            dgv_kddh.Columns["scenarios"].Visible = false;
            dgv_kddh.Columns["printBegin"].Visible = false;
            dgv_kddh.Columns["printEnd"].Visible = false;
            dgv_kddh.Columns["wzh"].Visible = false;
            dgv_kddh.Columns["bm"].Visible = false;
            dgv_kddh.Columns["isCheck"].HeaderText = "选择";
            dgv_kddh.Columns["mailNo"].HeaderText = "面单号";
            dgv_kddh.Columns["mailno_zd"].HeaderText = "子单";
            dgv_kddh.Columns["sendMan"].HeaderText = "寄件人姓名";
            dgv_kddh.Columns["sendManPhone"].HeaderText = "寄件人电话";
            dgv_kddh.Columns["sendManAddress"].HeaderText = "寄件人地址";
            dgv_kddh.Columns["sendPostcode"].HeaderText = "寄件邮编";
            dgv_kddh.Columns["sendProvince"].HeaderText = "寄件省";
            dgv_kddh.Columns["sendCity"].HeaderText = "寄件市";
            dgv_kddh.Columns["sendCounty"].HeaderText = "寄件区县";
            dgv_kddh.Columns["receiveMan"].HeaderText = "收件人姓名";
            dgv_kddh.Columns["receiveManPhone"].HeaderText = "收件人电话";
            dgv_kddh.Columns["receiveManAddress"].HeaderText = "收件人地址";
            dgv_kddh.Columns["receiveCompany"].HeaderText = "客户名";
            dgv_kddh.Columns["receivePostcode"].HeaderText = "收件邮编";
            dgv_kddh.Columns["receiveProvince"].HeaderText = "收件省";
            dgv_kddh.Columns["receiveCity"].HeaderText = "收件市";
            dgv_kddh.Columns["receiveCounty"].HeaderText = "收件区/县";
            dgv_kddh.Columns["shipName"].HeaderText = "业务名称";
            dgv_kddh.Columns["shipVal"].HeaderText = "服务金额";
            dgv_kddh.Columns["itemName"].HeaderText = "品名";
            dgv_kddh.Columns["itemWeight"].HeaderText = "重量";
            dgv_kddh.Columns["insuranceValue"].HeaderText = "保价金额";
            dgv_kddh.Columns["itemCount"].HeaderText = "数量";
            dgv_kddh.Columns["remark"].HeaderText = "备注";
            dgv_kddh.Columns["kdCompanys"].HeaderText = "快递公司";
            dgv_kddh.Columns["payMethod"].HeaderText = "支付方式";
            dgv_kddh.Columns["isReturnNo"].HeaderText = "是否签回单";
            dgv_kddh.Columns["printNum"].HeaderText = "打印数量";
            dgv_kddh.Columns["isPrint"].HeaderText = "是否已打印";
            dgv_kddh.Columns["isCancel"].HeaderText = "是否已取消";
            dgv_kddh.Columns["insertDate"].HeaderText = "插入时间";
            dgv_kddh.Columns["insertDate"].MinimumWidth = 120;
            foreach (DataGridViewColumn col in dgv_kddh.Columns)
            {
                if (col.Name != "isCheck" && col.Name != "printNum")
                {
                    col.ReadOnly = true;
                }
            }
        }
        private void Init()
        {
            string company = ConfigurationManager.AppSettings["curCompany"].ToString();
            list_kddh = DbUtil.Kddh_Query(dtp_begin.Value, dtp_end.Value, scenariosType, company);

            List<string> kdcomp = new List<string>();
            kdcomp.Add("全部");
            kdcomp.AddRange(list_kddh.Select(k => k.kdCompanys).Where(k => !string.IsNullOrEmpty(k)).Distinct().ToList());
            cb_kdCompany.DataSource = kdcomp;

            ShowView();
        }
        private void ShowView()
        {
            if (list_kddh == null)
            {
                return;
            }

            bool showPrint = chb_showPrinted.Checked;
            bool showCancel = chb_showCanceled.Checked;
            list_kddh_show = list_kddh.Where(k => (showPrint || (!showPrint && k.isPrint == "否")) && (showCancel || (!showCancel && k.isCancel == "否"))).ToList().Select(i => (Kddh)i.Clone()).ToList();

            string text = tb_search_kddh.Text;
            string kdcompanys = cb_kdCompany.Text;
            SortableBindingList<Kddh> ds = new SortableBindingList<Kddh>(list_kddh_show.Where(
                k => (k.mailNo.Contains(text)
                || k.sendMan.Contains(text)
                || k.sendManPhone.Contains(text)
                || k.sendManAddress.Contains(text)
                || k.receiveMan.Contains(text)
                || k.receiveManPhone.Contains(text)
                || k.receiveManAddress.Contains(text)
                || k.itemName.Contains(text)
                || k.itemWeight.Contains(text)
                || k.itemCount.Contains(text)
                || k.remark.Contains(text))
                && (kdcompanys == "全部" ? true : k.kdCompanys == kdcompanys)
                ).ToList());
            dgv_kddh.DataSource = ds;

            if (text.Length > 0)
            {
                SetCellsColor(dgv_kddh, text);
            }
        }
        private void SetCellsColor(DataGridView dgv, string text)
        {
            for (int r = 0; r < dgv.Rows.Count; r++)
            {
                for (int c = 0; c < dgv.Columns.Count; c++)
                {
                    if (dgv.Rows[r].Cells[c].Value != null && dgv.Rows[r].Cells[c].Value.ToString().Contains(text))
                    {
                        dgv.Rows[r].Cells[c].Style.BackColor = Color.YellowGreen;
                    }
                }
            }
        }
        private bool CheckPrint(List<Kddh> selectKddhs)
        {
            if (selectKddhs == null || selectKddhs.Count == 0)
            {
                MessageBox.Show("请选择快递单号", "提示");
                return false;
            }
            return true;
        }
        private bool CheckCancel(List<Kddh> selectKddhs)
        {
            if (selectKddhs == null || selectKddhs.Count == 0)
            {
                MessageBox.Show("请选择快递单号", "提示");
                return false;
            }
            if (selectKddhs.Where(k => k.isCancel == "是").ToList().Count > 0)
            {
                MessageBox.Show("存在已取消的快递单号,请重新选择.", "提示");
                return false;
            }
            return true;
        }
        private void SetSelectedRowCheck(DataGridView dgv, DataGridViewSelectedRowCollection rows, bool b)
        {
            dgv.EndEdit();
            foreach (DataGridViewRow row in rows)
            {
                Kddh k = (Kddh)row.DataBoundItem;
                k.isCheck = b;
            }
            dgv.Refresh();
        }
        private void SetRowCheck(DataGridView dgv, DataGridViewRowCollection rows, bool b)
        {
            dgv.EndEdit();
            foreach (DataGridViewRow row in rows)
            {
                Kddh k = (Kddh)row.DataBoundItem;
                k.isCheck = b;
            }
            dgv.Refresh();
        }
        #endregion

        #region 事件
        private void KddhForm_Load(object sender, EventArgs e)
        {
            mainForm.btn_bro.Enabled = false;
            InitCtrl();
            Init();
        }
        private void btn_search_Click(object sender, EventArgs e)
        {
            Init();
        }
        private void tb_search_kddh_TextChanged(object sender, EventArgs e)
        {
            ShowView();
        }
        private void chb_showPrinted_CheckedChanged(object sender, EventArgs e)
        {
            ShowView();
        }
        private void chb_showCanceled_CheckStateChanged(object sender, EventArgs e)
        {
            ShowView();
        }
        private void cb_kdCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowView();
        }
        private void btn_print_Click(object sender, EventArgs e)
        {
            List<Kddh> selectKddhs = list_kddh_show.Where(l => l.isCheck == true).ToList();
            if (CheckPrint(selectKddhs))
            {
                ChoosePrinter choosePrinter = new ChoosePrinter(selectKddhs);
                if (choosePrinter.ShowDialog(this) == DialogResult.Yes)
                {
                    dgv_kddh.EndEdit();
                    foreach (Kddh k in selectKddhs)
                    {
                        k.isPrint = "是";
                    }
                    dgv_kddh.Refresh();
                }
            }
        }
        private void btn_printAny_Click(object sender, EventArgs e)
        {
            List<Kddh> selectKddhs = list_kddh_show.Where(l => l.isCheck == true).ToList();
            if (CheckPrint(selectKddhs))
            {
                ChoosePrintNum choosePrintNum = new ChoosePrintNum(selectKddhs);
                if (choosePrintNum.ShowDialog(this) == DialogResult.Yes)
                {
                    Init();
                }
            }
        }
        private void btn_cancel_Click(object sender, EventArgs e)
        {
            List<Kddh> selectKddhs = list_kddh_show.Where(l => l.isCheck == true).ToList();
            if (CheckCancel(selectKddhs) && MessageBox.Show("确定取消所选快递单号?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                foreach (Kddh k in selectKddhs)
                {
                    if (ExpressUtil.CancelMailNo(k))
                    {
                        Init();
                    }
                }
            }
        }
        private void 选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSelectedRowCheck(dgv_kddh, dgv_kddh.SelectedRows, true);
        }
        private void 取消选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSelectedRowCheck(dgv_kddh, dgv_kddh.SelectedRows, false);
        }
        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetRowCheck(dgv_kddh, dgv_kddh.Rows, true);
        }
        private void 全部取消ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetRowCheck(dgv_kddh, dgv_kddh.Rows, false);
        }
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Init();
        }
        private void KddhForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ConfigUtil.SetValue("isShowPrint", chb_showPrinted.Checked.ToString());
            ConfigUtil.SetValue("isShowCancel", chb_showCanceled.Checked.ToString());
        }
        private void 运单信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Kddh k = (Kddh)dgv_kddh.SelectedRows[0].DataBoundItem;
            TraceForm t = new TraceForm(k);
            t.ShowDialog(this);
        }
        private void btn_export_Click(object sender, EventArgs e)
        {
            SortableBindingList<Kddh> list = (SortableBindingList<Kddh>)dgv_kddh.DataSource;
            DataTable dt = new DataTable();
            dt.Columns.Add("面单号");
            dt.Columns.Add("寄件人姓名");
            dt.Columns.Add("寄件人电话");
            dt.Columns.Add("寄件人地址");
            dt.Columns.Add("寄件邮编");
            dt.Columns.Add("寄件省");
            dt.Columns.Add("寄件市");
            dt.Columns.Add("寄件区县");
            dt.Columns.Add("收件人姓名");
            dt.Columns.Add("收件人电话");
            dt.Columns.Add("收件人地址");
            dt.Columns.Add("收件邮编");
            dt.Columns.Add("收件省");
            dt.Columns.Add("收件市");
            dt.Columns.Add("收件区县");
            dt.Columns.Add("业务名称");
            dt.Columns.Add("服务金额");
            dt.Columns.Add("品名");
            dt.Columns.Add("重量");
            dt.Columns.Add("数量");
            dt.Columns.Add("备注");
            dt.Columns.Add("快递公司");
            dt.Columns.Add("打印数量");
            dt.Columns.Add("是否已打印");
            dt.Columns.Add("是否已取消");
            dt.Columns.Add("插入时间");

            foreach (Kddh k in list)
            {
                DataRow row = dt.NewRow();
                row["面单号"] = k.mailNo;
                row["寄件人姓名"] = k.sendMan;
                row["寄件人电话"] = k.sendManPhone;
                row["寄件人地址"] = k.sendManAddress;
                row["寄件邮编"] = k.sendPostcode;
                row["寄件省"] = k.sendProvince;
                row["寄件市"] = k.sendCity;
                row["寄件区县"] = k.sendCounty;
                row["收件人姓名"] = k.receiveMan;
                row["收件人电话"] = k.receiveManPhone;
                row["收件人地址"] = k.receiveManAddress;
                row["收件邮编"] = k.receivePostcode;
                row["收件省"] = k.receiveProvince;
                row["收件市"] = k.receiveCity;
                row["收件区县"] = k.receiveCounty;
                row["业务名称"] = k.shipName;
                row["服务金额"] = k.shipVal;
                row["品名"] = k.itemName;
                row["重量"] = k.itemWeight;
                row["数量"] = k.itemCount;
                row["备注"] = k.remark;
                row["快递公司"] = k.kdCompanys;
                row["打印数量"] = k.printNum;
                row["是否已打印"] = k.isPrint;
                row["是否已取消"] = k.isCancel;
                row["插入时间"] = k.insertDate;
                dt.Rows.Add(row);
            }
            ExcelHelper.ExportDataToExcel(dt, "快递单号信息");
        }
        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(ClickCellVal ?? "");
        }
        private void dgv_kddh_MouseUp(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo info = dgv_kddh.HitTest(e.X, e.Y);
            if (info.RowIndex >= 0 && info.ColumnIndex >= 0)
            {
                ClickCellVal = dgv_kddh.Rows[info.RowIndex].Cells[info.ColumnIndex].Value.ToString();
            }
        }
        private void KddhForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            mainForm.btn_bro.Enabled = true;
        }
        #endregion
    }
}
